package com.huawei.cloud.phone.management.adapter.utils;

import com.huawei.cloud.phone.management.common.utils.Constants;
import com.huawei.cloud.phone.management.domain.user.User;
import org.springframework.lang.NonNull;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class HttpUtils {

    /**
     * 从HTTP header中获取参数
     *
     * @param key 参数名称
     * @return 参数值
     */
    public static Optional<String> getDataFromHeader(@NonNull String key) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            return Optional.ofNullable(request.getHeader(key));
        }
        return Optional.empty();
    }

    /**
     * 从HTTP header中通过token获取用户ID
     *
     * @return 用户ID
     */
    public static Optional<String> getUserId() {
        Optional<String> token = getDataFromHeader(Constants.TOKEN);
        return token.map(User::parseUserId);
    }
}
